#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h> 
#define PUBLIC_FIFO "MYFIFO"
#define PRIVATE1 "P_FO1"
#define PRIVATE2 "P_FO2"
#define PRIVATE1_HEADER "private 1 > "
#define PRIVATE2_HEADER "private 2 > "
#define SERVER_REPLY "Server Copy That (from server)"

int main(){
    int fd1;
    int fd2;
    int fd3;
    char p1[20]="Hello, Client1";
    char p2[20]="Hello, Client2";
    char readbuf[80];

    umask(0);
    mknod(PUBLIC_FIFO,S_IFIFO|0666,0);
    mknod(PRIVATE1,S_IFIFO|0666,0);
    mknod(PRIVATE2,S_IFIFO|0666,0);

    fd2=open(PRIVATE1,O_CREAT|O_WRONLY);
    fd3=open(PRIVATE2,O_CREAT|O_WRONLY);
    if(write(fd2, p1, strlen(p1)) <= 0){
        printf("Fail to write fd2\n");
        exit(1);
    }
    if(write(fd3, p2, strlen(p2)) <=0){
        printf("Fail to write fd3\n");
        exit(1);
    }
    close(fd2);
    close(fd3);
    //printf("Closed Private FIFO\n");
    printf("Write init data to client\n\n");

    while(1){
        if((fd1=open(PUBLIC_FIFO,O_RDWR))==-1){
            printf("open fifi failed\n" );
            exit(1);
        }
        if(read(fd1, readbuf, 220)!=-1)
        {
            //printf("Received string :%s\n", readbuf);
            printf("%s", readbuf);
            close(fd1);
        }

        usleep(200000);

        if(strncmp(readbuf, PRIVATE1_HEADER, strlen(PRIVATE1_HEADER)) == 0){
            //printf("Recive from Client1\n\n");
            if((fd2=open(PRIVATE1, O_WRONLY)) != -1){
                if(write(fd2, SERVER_REPLY, strlen(SERVER_REPLY)) <= 0){
                    printf("Fail to write fd2\n");
                    exit(1);
                }
            }
            close(fd2);
        }
        if(strncmp(readbuf, PRIVATE2_HEADER, strlen(PRIVATE2_HEADER)) == 0){
            //printf("Recive from Client1\n");
            if((fd3=open(PRIVATE2, O_WRONLY)) != -1){
                if(write(fd3, SERVER_REPLY, strlen(SERVER_REPLY)) <= 0){
                    printf("Fail to write fd3\n");
                    exit(1);
                }
            }
            close(fd3);
        }
    }
    return 0;
}